<?php
/**
 * User: hjd-yao
 * Date: 2019/5/6
 * Time: 10:47
 */

namespace Develop\Http\Controllers;


use App\Helpers\SelfResponse;
use App\Http\Controllers\Controller;
use Develop\Models\ChangeTypeModel;
use Illuminate\Http\Request;

class ChangeTypeController extends Controller
{
    public function changes()
    {
        $list = ChangeTypeModel::get();
        return view('develop::change.list',[
            'page_title'=>'变更类型',
            'list'=>$list
        ]);
    }

    public function create(Request $request)
    {
        if($request->isMethod('post')){
            $changeType = new ChangeTypeModel();
            if(!$changeType->addType($request)){
                return SelfResponse::error($changeType->getErrorMsg('添加失败'));
            }
            return SelfResponse::success('添加成功','d_ChangeType_changes');
        }else{
            return view('develop::change.add_or_edit',[
                'page_title'=>'添加更改类型',
                'url'=>url()->current()
            ]);
        }
    }

    public function update(Request $request, $id)
    {
        if($request->isMethod('post')){
            $changeType = new ChangeTypeModel();
            if(!$changeType->editType($request,$id)){
                return SelfResponse::error($changeType->getErrorMsg('更新失败'));
            }
            return SelfResponse::success('更新成功','d_ChangeType_changes');
        }else{
            $info = ChangeTypeModel::find($id);
            return view('develop::change.add_or_edit',[
                'page_title'=>'编辑变更类型',
                'info'=>$info,
                'url'=>url()->current()
            ]);
        }
    }

    public function delete(Request $request)
    {
        $ids = $request->input('type_id');
        $ids = array_filter(is_array($ids)?$ids:str2arr($ids));
        if(!$ids){
            return SelfResponse::error('请选择要操作的数据');
        }

        if(!ChangeTypeModel::whereIn('id',$ids)->delete()){
            return SelfResponse::error('删除失败请稍后再试');
        }
        return SelfResponse::success('删除成功','d_ChangeType_changes');
    }

    public function switchType($id)
    {
        $info = ChangeTypeModel::find($id);
        if(!$info){
            return SelfResponse::error('操作的类型不存在');
        }
        $info->status = abs($info->status - 1);
        if($info->save()){
            return SelfResponse::success('操作成功','d_ChangeType_changes');
        }
        return SelfResponse::error('操作失败');
    }
}